/*
* @Author: liqs
* @Date:   2020/12/22 上午10:48
 */
package main

import (
	"fmt"
	"learn-use-go/useFabricsdk/methods"
	"os"
	"time"
)

var (
	channelID = "txchannel"
	ccID      = "test4"
	orgName   = "OrgA"
	ueserId   = "Admin"
	//putRecordByKey = "PutStringRecordByKey"
	putRecordByKey = "PutStringRecordByKeyTest"
	getRecordByKey = "GetRecordByKey"
	putargs        = [][]byte{[]byte("key1121"), []byte("value")}
	queryargs      = [][]byte{[]byte("key")}
	configfilepath = "/home/blockchain/GOPATH/src/learn-use-go/useFabricsdk/config-linux.yaml"
)

func main() {
	starttime := time.Now()
	client := methods.GetChannelClient(channelID, orgName, ueserId, configfilepath)
	// grpc 的最大连接数为2500  需要做限制  当数字太大就会出问题
	totalnum := 10000
	recordChan := make(chan int, 10000)
	// 该通道就是为了防止开的协程数量过多准备
	goroutinNum := make(chan int, 10000)
	// 开协程执行
	num := 0
	for i := 0; i < totalnum; i++ {
		if len(goroutinNum) < 2500 {
			// 开一个协程就放入一个数字，计算长度
			// 同样，完成一个协程就取出一个数，只要当前开的协程数小于约定的数即可
			goroutinNum <- 1
			go methods.Invoke(client, ccID, putRecordByKey, putargs, recordChan)
		} else {
			// 因为此循环没有开协程 ，必须减1
			i--
			// 因为执行完一个协程就会写入一个数据，现在能取出来说明已经执行完一条交易
			// 然后计数为num ，当 num 为总数时就结束
			_, ok := <-recordChan
			<-goroutinNum
			if ok {
				num++
				if num == totalnum {
					os.Exit(0)
				}
			}
		}
	}
	// 确保协程执行完
	methods.Ensureend(recordChan, goroutinNum, totalnum, num)
	since := time.Since(starttime)
	fmt.Println("spend time = ", since)
	fmt.Println("tps =  ", (totalnum)/(int(since)/1000000000))
}
